package com.nfit.shopweb.service.impl;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.nfit.shopmodel.entity.product.Category;
import com.nfit.shopmodel.vo.product.CategoryExcelVo;
import com.nfit.shopweb.listener.CategoryListener;
import com.nfit.shopweb.mapper.CategoryMapper;
import com.nfit.shopweb.service.CategoryService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * ClassName:CategoryServiceImpl
 * Package:com.nfit.shopweb.service.impl
 * Description
 *
 * @Author L
 * @Create 2024/12/9 9:57
 */
@Service
@Slf4j
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 根据parentId 查询数据
     */
    @Override
    public List<Category> selectByParentIdTreeCategory(Integer parentId) {
        //这里后端直接传0 ,0 表示父级分类菜单
        List<Category> categoryList = categoryMapper.selectByParentIdTreeCategory(parentId);
        //判断categoryList不为null
        if (!CollectionUtil.isEmpty(categoryList)) {
            //遍历categoryList
            categoryList.forEach(category -> {
                //遍历一级商品分类菜单,根据一级商品分类id查询子节点
                //约定：一级商品分类parentId = 0 表示 一级商品分类,一级商品分类id = 商品分类对象的parentId 表示下级节点(二级商品分类)
                //同理：二级商品分类id = 商品分类对象的parentId 表示下级节点(三级商品分类id)
                Integer size = categoryMapper.getTreeCategoryChildren(category.getId());
                if (size > 0) {
                    category.setHasChildren(true);
                } else {
                    category.setHasChildren(false);
                }
            });
        }
        return categoryList;
    }

    /**
     * 导出：表示从数据库读数据到excel的过程是导出
     *
     * @param response 响应对象
     */
    @Override
    public void exportData(HttpServletResponse response) {
        try {
            // 设置响应类型为 Excel 文件
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

            // 设置文件名，防止中文乱码
            String fileName = URLEncoder.encode("商品分类数据表格", "utf-8").replaceAll("\\+", "%20");
            response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx\"");


            // 从数据库读取数据
            List<Category> categoryList = categoryMapper.selectAll();
            List<CategoryExcelVo> categoryExcelVoList = new ArrayList<>(categoryList.size());

            // 将数据转化为 Excel 格式
            categoryList.forEach(category -> {
                CategoryExcelVo categoryExcelVo = new CategoryExcelVo();
                BeanUtils.copyProperties(category, categoryExcelVo, CategoryExcelVo.class);
                categoryExcelVoList.add(categoryExcelVo);
            });
            log.info("开始写入 Excel 文件...");
            // 写入到输出流
            EasyExcel.write(response.getOutputStream(), CategoryExcelVo.class)
                    .autoCloseStream(false)
                    .sheet("商品分类数据表格")
                    .doWrite(categoryExcelVoList);
            log.info("Excel 文件写入完毕！");
        } catch (Exception e) {
            log.error("导出失败", e);
            e.printStackTrace();
        }
    }

    /**
     * 从excel文件中读取数据添加到数据库中
     * @param file 文件输入流
     */
    @Override
    public void exportSave(MultipartFile file, HttpServletResponse response) {

        try {
            response.setContentType("text/html;charset=utf-8");
            log.info("开始存入数据库：{}", file.getOriginalFilename());
            EasyExcel.read(file.getInputStream(), Category.class, new CategoryListener(categoryMapper)).sheet().doRead();
            log.info("结束存入数据库：{}", file.getOriginalFilename());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
